<template>
	<view class="add-repair-container">
		<up-form
			:model="form"
			:rules="rules"
			ref="formRef"
			label-width="100"
		>
			<up-form-item
				label="设备名称"
				prop="equipmentId"
				border-bottom
			>
				<div class="flexed">
					<div
						v-if="equipmentName.length > 0"
						class="showText"
					>
						{{ equipmentName }}
					</div>
					<up-button
						type="primary"
						@click="equipmentShow = true"
						class="showBtn"
						>选择设备名称</up-button
					>
				</div>
			</up-form-item>

			<up-form-item
				label="故障类型"
				prop="faultType"
				border-bottom
			>
				<div class="flexed">
					<div v-if="fultText.length > 0" class="showText">
						{{ fultText }}
					</div>
					<up-button
						type="primary"
						@click="fultShow = true"
						class="showBtn"
						>选择故障类型</up-button
					>
				</div>
			</up-form-item>

			<up-form-item
				label="报修人"
				prop="reporter"
				border-bottom
			>
				<up-input
					v-model="form.reporter"
					placeholder="请输入报修人"
				/>
			</up-form-item>

			<up-form-item
				label="问题描述"
				prop="faultDescription"
				border-bottom
			>
				<up-textarea
					v-model="form.faultDescription"
					placeholder="请详细描述设备问题"
				/>
			</up-form-item>

			<up-form-item label="上传图片" prop="equipmentImg">
				<up-upload
					:fileList="form.equipmentImg"
					@afterRead="handleAfterRead"
					@delete="handleDeleteImage"
					multiple
					maxCount="3"
				></up-upload>
			</up-form-item>
		</up-form>

		<up-picker
			v-model:show="fultShow"
			:columns="fultTypeList"
			keyName="label"
			@confirm="confirmFultType"
			closeOnClickOverlay
		></up-picker>

		<up-picker
			v-model:show="equipmentShow"
			:columns="equipmentList"
			keyName="label"
			@confirm="confirmEquipment"
			closeOnClickOverlay
		></up-picker>

		<view class="submit-btn">
			<up-button
				type="primary"
				text="提交报修"
				@click="handleSubmit"
			></up-button>
		</view>
	</view>
</template>

<script setup>
import { onMounted, ref } from "vue";
import {
	listRepair,
	getRepair,
	delRepair,
	addRepair,
	updateRepair,
	repairEquipment,
	listEquipment
} from "@/api/repair";
import {
	getUserInfo,
	updateUserInfo,
	logout
} from "@/api/user";

const fultTypeList = ref([
	[
		{ label: "机械故障", id: "1" },
		{ label: "电气故障", id: "2" },
		{ label: "软件故障", id: "3" },
		{ label: "人为损坏", id: "4" },
		{ label: "自然老化", id: "5" }
	]
]);
const fultShow = ref(false);
const fultText = ref("");

const equipmentList = ref([]);
const equipmentShow = ref(false);
const equipmentName = ref("");
const getEquipmentList = async () => {
	const res = await listEquipment({
		pageNum: 1,
		pageSize: 100
	});
	console.log(res.data.rows);
	equipmentList.value[0] = res.data.rows.map((res) => {
		return {
			label: res.name,
			id: res.equipmentId
		};
	});
};

const userInfo = ref({});
const getUser = async () => {
	const res = await getUserInfo();
	userInfo.value = res.data.user;
	console.log("111111111",userInfo.value);
	form.value.reporter = res.data.user.nickName
};

const form = ref({
	equipmentId: "",
	faultType: "",
	faultDescription: "",
	equipmentImg: []
});

const rules = {
	faultDescription: [
		{
			required: true,
			message: "请输入问题描述",
			trigger: "blur"
		}
	]
};

const formRef = ref();

onMounted(() => {
	getEquipmentList();
	getUser()
});

// 确定故障类型
function confirmFultType(e) {
	form.value.faultType = e.value[0].id;
	fultText.value = e.value[0].label;
}

// 确定设备
function confirmEquipment(e) {
	form.value.equipmentId = e.value[0].id;
	equipmentName.value = e.value[0].label;
}

// 图片上传处理
const handleAfterRead = async (event) => {
	const { file } = event;
	const files = Array.isArray(file) ? file : [file];

	for (const item of files) {
		try {
			// 添加到表单中，状态设置为uploading
			const tempFile = {
				url: item.url, // 本地预览地址
				status: "uploading",
				message: "上传中..."
			};
			form.value.equipmentImg.push(tempFile);

			// 调用uni-app上传方法
			const res = await uploadFileToServer(item);

			// 更新状态
			const index = form.value.equipmentImg.findIndex(
				(img) => img.url === item.url
			);
			if (index !== -1) {
				form.value.equipmentImg[index] = {
					url: res.data.url, // 服务器返回的URL
					status: "success",
					message: "上传成功"
				};
			}
		} catch (error) {
			console.error("上传失败:", error);
			const index = form.value.equipmentImg.findIndex(
				(img) => img.url === item.url
			);
			if (index !== -1) {
				form.value.equipmentImg[index] = {
					url: item.url,
					status: "failed",
					message: "上传失败"
				};
			}
			showToast("上传失败，请重试");
		}
	}
};

// 使用uni-app的上传方法
const uploadFileToServer = (file) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync("token");
		uni.uploadFile({
			url: "http://localhost:8080/common/upload", // 替换为你的实际接口地址
			filePath: file.url, // 本地文件路径
			header: {
				Authorization: token
			},
			name: "file", // 后端接收文件的字段名
			formData: {
				// 可以添加其他表单参数
				// key1: 'value1',
				// key2: 'value2'
			},
			success: (res) => {
				// 假设返回的是JSON字符串
				const data = JSON.parse(res.data);
				resolve({ data });
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};

// 删除图片
const handleDeleteImage = (event) => {
	form.value.equipmentImg.splice(event.index, 1);
};

// 提交表单
const handleSubmit = () => {
	formRef.value
		.validate()
		.then(async () => {
			uni.showLoading({
				title: "提交中..."
			});
			if (form.value.equipmentId.length === 0) {
				uni.showToast({
					title: "请选择设备"
				});
			}
			console.log(form.value.equipmentImg);
			form.value.equipmentImg = form.value.equipmentImg?.map(res=>res.url).join(",")
			await addRepair(form.value);
			// 模拟API请求
			uni.hideLoading();
			uni.showToast({
				title: "报修成功",
				icon: "success"
			});

			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		})
		.catch((errors) => {
			console.log("表单验证失败:", errors);
		});
};
</script>

<style lang="scss" scoped>
.add-repair-container {
	padding: 20rpx;

	.submit-btn {
		margin-top: 40rpx;
		padding: 0 20rpx;
	}
}
.flexed {
	display: flex;
	align-items: center;
	.showText {
		width: 300rpx;
	}
}
</style>
